package com.zzyl.nursing.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.domain.entity.SysUser;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.framework.config.properties.HuaWeiIotConfigProperties;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IDeviceService;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.ProductVo;
import com.zzyl.system.service.ISysUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 设备信息Service业务层处理
 * 
 * @author Nuyoah
 * @date 2025-05-25
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService
{
    @Autowired
    private DeviceMapper deviceMapper;

    /**
     * 查询设备信息
     * 
     * @param id 设备信息主键
     * @return 设备信息
     */
    @Override
    public Device selectDeviceById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询设备信息列表
     * 
     * @param device 设备信息
     * @return 设备信息
     */
    @Override
    public List<Device> selectDeviceList(Device device)
    {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备信息
     * 
     * @param device 设备信息
     * @return 结果
     */
    @Override
    public int insertDevice(Device device)
    {
        return save(device) ? 1 : 0;
    }

    /**
     * 修改设备信息
     * 
     * @param device 设备信息
     * @return 结果
     */
    @Override
    public int updateDevice(Device device)
    {
        return updateById(device) ? 1 : 0;
    }

    /**
     * 批量删除设备信息
     * 
     * @param ids 需要删除的设备信息主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备信息信息
     * 
     * @param id 设备信息主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private IoTDAClient client;
    /**
     * 同步物联网平台产品列表
     */
    @Override
    public void syncProductList() {
        //1.从物联网平台同步产品列表数据
        ListProductsResponse response = client.listProducts(new ListProductsRequest());
        if (response.getHttpStatusCode()!=200||response==null){
            throw new RuntimeException("获取产品列表失败");
        }
        //2.获取Response中的product内容,将其存入Redis中
        List<ProductSummary> productList = response.getProducts();
        redisTemplate.opsForValue().set(CacheConstants.IOT_PRODUCT_LIST_KEY, JSONUtil.toJsonStr(productList));
    }

    /**
     * 查询所有产品列表
     *
     * @return
     */
    @Override
    public List<ProductVo> allProduct() {
        //1.从Redis中获取产品列表数据
        String productListJSON = redisTemplate.opsForValue().get(CacheConstants.IOT_PRODUCT_LIST_KEY);
        if (StringUtils.isBlank(productListJSON)){
            throw new BaseException("获取产品列表失败");
        }
        //2.解析JSON对象
        List<ProductSummary> productSummaryList = JSONUtil.toList(productListJSON, ProductSummary.class);

        //3.封装为ProjectVo对象
        List<ProductVo> productVoList = productSummaryList.stream().map(x -> {
            return ProductVo.builder().productName(x.getName()).productKey(x.getProductId()).build();
        }).collect(Collectors.toList());

        //4.返回数据
        return productVoList;
    }

    /**
     * 注册设备
     *
     * @param dto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void registerDevice(DeviceDto dto) {
        //1.判断设备名称是否重复
        Long deviceCount = this.lambdaQuery().eq(Device::getDeviceName, dto.getDeviceName()).count();
        if (deviceCount>0){
            throw new BaseException("设备名称重复,不允许注册");
        }

        //2.判断设备标识是否重复
        String nodeId = IdUtil.getSnowflakeNextIdStr();//使用雪花算法生成长度为19为的数字(全球唯一)
        Long nodeIdCount = this.lambdaQuery().eq(Device::getNodeId, nodeId).count();
        if (nodeIdCount>0){
            throw new BaseException("设备标识重复,不允许注册");
        }

        //3.判断同一位置是都绑定了相同的产品
        Long productCount = this.lambdaQuery().eq(Device::getProductKey, dto.getProductKey())
                .eq(Device::getLocationType, dto.getLocationType())
                .eq(Device::getBindingLocation, dto.getBindingLocation()).count();
        if (productCount>0){
            throw new BaseException("同一位置绑定了相同的产品,不允许注册");
        }

        //4.调用IOT接口注册设备
        AddDeviceRequest request = new AddDeviceRequest();
        AddDevice body = new AddDevice();
        body.setNodeId(nodeId);//设置设备标识
        body.setProductId(dto.getProductKey());//设置产品ID
        body.setDeviceName(dto.getDeviceName());//设备名称
        String description = dto.getRegisterDeviceRequest().getNickname();
        body.setDescription(description);//设备描述（设备备注）
        String secret = IdUtil.fastSimpleUUID();//生成密钥(UUID唯一值)
        AuthInfo authInfo = new AuthInfo();
        authInfo.setSecret(secret);
        body.setAuthInfo(authInfo);//设置密钥

        request.withBody(body);

        //5.发起设备请求,得到响应结果
        AddDeviceResponse response = client.addDevice(request);
        if (response.getHttpStatusCode()!=201||response == null){
            throw new BaseException("调用华为云获取结果异常!");
        }

        //6.解析响应结果,保存数据到本地
        String iotId = response.getDeviceId();
        Device device = new Device();
        BeanUtils.copyProperties(dto, device);
        device.setIotId(iotId);//物联网设备ID
        device.setSecret(secret);//设置密钥
        device.setNodeId(nodeId);//设备标识符
        device.setDeviceDescription(description);//设备描述
        device.setNickname(description); //设备备注
        String productName = getProductName(dto.getProductKey());
        device.setProductName(productName);
        boolean result = this.save(device);
        if (!result){
            throw new BaseException("保存设备数据失败");
        }
    }

    /**
     * 根据产品ID在Redis中查询出产品名称
     * @param productKey
     * @return
     */
    private String getProductName(String productKey) {
        //1.从Redis中获取Json数据
        String productJSON = redisTemplate.opsForValue().get(CacheConstants.IOT_PRODUCT_LIST_KEY);
        //2.解析JSON数据为产品列表
        List<ProductSummary> productSummaryList = JSONUtil.toList(productJSON, ProductSummary.class);

        //3.过滤获取产品ID与productKey值相同的产品
        ProductSummary productSummary = productSummaryList.stream().filter(x -> x.getProductId().equals(productKey)).findFirst().get();

        //4.返回产品的名称
        if (productSummary!=null){
            return productSummary.getName();
        }
        return null;
    }

    @Autowired
    private HuaWeiIotConfigProperties huaWeiIotConfigProperties;
    @Autowired
    private ISysUserService userService;
    /**
     * 查看设备详情
     *
     * @param iotId
     * @return
     */
    @Override
    public DeviceDetailVo queryDeviceDetail(String iotId) {
        //1.根据设备ID判断设备是否存在
        Device device = this.lambdaQuery().eq(Device::getIotId, iotId).one();
        if (device==null){
            throw new BaseException("查询设备失败,暂无该设备");
        }

        //2.拷贝device对象到DeviceDetailVo对象中
        DeviceDetailVo vo = new DeviceDetailVo();
        BeanUtils.copyProperties(device, vo);

        //3.补充一些必要的属性
        vo.setDeviceSecret(device.getSecret());//设备密钥
        vo.setGmtCreate(device.getCreateTime());//创建时间
        vo.setRegion(huaWeiIotConfigProperties.getRegionId());//区域ID
        SysUser sysUser = userService.selectUserById(Long.valueOf(device.getCreateBy()));
        vo.setCreator(sysUser.getUserName());//设置创建人

        //4.调用华为云IOT平台中获取数据
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.withDeviceId(iotId);//设备ID
        ShowDeviceResponse response = client.showDevice(request);
        if (response==null||response.getHttpStatusCode()!=200){
            throw new BaseException("调用华为云获取信息失败");
        }

        //5.补充必要的属性值
        vo.setDeviceStatus(response.getStatus());//设备状态
        vo.setStatus(response.getStatus());//设备状态
        //设备激活时间。格式：yyyy-MM-dd'T'HH:mm:ss.SSS'Z' ，如2015-12-12T12:12:122Z。这种时间是国际标准时区的时间，比东八区（亚洲/上海）早8小时
        String activeTime = response.getActiveTime();
        if (StringUtils.isNotBlank(activeTime)){
            LocalDateTime gmtActiveTime = OffsetDateTime.parse(activeTime).atZoneSameInstant(ZoneId.of("Asia/Shanghai")).toLocalDateTime();
            vo.setGmtActive(gmtActiveTime);//设置激活时间
        }
        vo.setFirmwareVersion(response.getFwVersion());//固件版本

        //返回DeviceDetailVo对象
        return vo;
    }

    /**
     * 查看指定产品的已发布物模型中的功能定义详情
     *
     * @param productKey
     * @return
     */
    @Override
    public JSONObject queryProductModelInfo(String productKey) {
        //1.从华为云中获取数据
        ShowProductRequest request = new ShowProductRequest();
        request.withProductId(productKey);
        ShowProductResponse response = client.showProduct(request);
        if (response==null||response.getHttpStatusCode()!=200){
            throw new BaseException("调用华为云接口失败");
        }
        //2.解析响应结果
        List<ServiceCapability> serviceCapabilities = response.getServiceCapabilities();
        if (serviceCapabilities==null){
            throw new BaseException("获取物模型数据失败");
        }
        ServiceCapability serviceCapability = serviceCapabilities.get(0);

        //3.进行数据转换
        JSONObject jsonObject = JSONUtil.parseObj(serviceCapability);
        return jsonObject;
    }

    /**
     * 查询指定设备的物模型运行状态
     *
     * @param deviceName
     * @return
     */
    @Override
    public Map<String, Object> queryDevicePropertyStatus(String deviceName) {
        //1.判断设备是否存在
        Device device = this.lambdaQuery().eq(Device::getDeviceName, deviceName).select(Device::getIotId).one();
        if (device==null){
            throw new BaseException("设备不存在,查询失败");
        }
        String deviceId = device.getIotId();//获取设备ID

        //2.调用华为云IOT接口查询影子数据
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.withDeviceId(deviceId);
        ShowDeviceShadowResponse response = client.showDeviceShadow(request);
        if (response==null||response.getHttpStatusCode()!=200){
            throw new BaseException("调用华为云IOT接口查询失败");
        }

        //3.解析响应结果,封装Map集合
        List<DeviceShadowData> shadowDataList = response.getShadow();//获取影子数据
        if (CollUtil.isEmpty(shadowDataList)){
            throw new BaseException("获取影子数据为空");
        }
        DeviceShadowData shadowData = shadowDataList.get(0);
        DeviceShadowProperties reported = shadowData.getReported();
        String eventTimeStr = reported.getEventTime();
        LocalDateTime eventTime = OffsetDateTime.parse(eventTimeStr, DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmssX"))
                .atZoneSameInstant(ZoneId.of("Asia/Shanghai")).toLocalDateTime();
        JSONObject properties = JSONUtil.parseObj(reported.getProperties());
        List<Map<String,Object>> propertyStatusInfo = new ArrayList<>();
        properties.forEach((k,v)->{
            //封装属性对象
            Map<String,Object> propertyMap = new HashMap<>();
            propertyMap.put("identifier", k);
            propertyMap.put("name", k);
            propertyMap.put("value", v);
            propertyMap.put("time", eventTime);
            propertyStatusInfo.add(propertyMap);
        });
        //4.返回Map数据
        Map<String,Object> resultMap = new HashMap<>();

        Map<String,Object> propertyStatusInfoMap = new HashMap<>();
        propertyStatusInfoMap.put("propertyStatusInfo", propertyStatusInfo);

        resultMap.put("list",propertyStatusInfoMap);

        return resultMap;
    }
}
